package com.duobeiyun.gmstest.work

import android.content.Context
import androidx.work.WorkerParameters
import com.duobeiyun.generamessagesdk.ErrorInfo
import com.duobeiyun.generamessagesdk.ResultCallback
import com.duobeiyun.generamessagesdk.bean.LoginParams
import com.duobeiyun.generamessagesdk.connect.Connect
import com.duobeiyun.generamessagesdk.utils.TokenUtils
import com.duobeiyun.gmstest.TestInstance
import com.duobeiyun.gmstest.log.LogDebug
import com.duobeiyun.gmstest.log.LogOuter
import com.duobeiyun.gmstest.work.sample.WorkAsyncMode
import kotlinx.coroutines.CancellableContinuation
import kotlin.coroutines.resume

/**
 * token过期后检查连接状态
 */
class WorkConnectStateByToken(appContext: Context, workerParams: WorkerParameters) :
        WorkAsyncMode(appContext, workerParams) {

    override fun setNumber() {
        TAG = "WorkConnectStateByToken"
        number = "9"
        timeout = 60 * 1000
    }

    override fun realWork(continuation: CancellableContinuation<Result>) {
        var userId = TestInstance.userId
        val timestamp = System.currentTimeMillis() - 1000 * 60 * 60 * 24 + 1000 * 5;
        val token = TokenUtils.createToke(TestInstance.TEST_APPID, userId, timestamp!!, TestInstance.TEST_APPKEY);
        TestInstance.login(LoginParams(token!!, userId!!, timestamp!!),
                object : ResultCallback<Void> {
                    override fun onSuccess(responseInfo: Void?) {
                        checkConnectState(Connect.CONNECTION_STATE_CONNECTED, Connect.CONNECTION_CHANGE_REASON_LOGIN_SUCCESS)
                        LogDebug.logD("TestInstance.connectStateCode:${TestInstance.connectStateCode} TestInstance.connectStateReason:${TestInstance.connectStateReason}")
                        LogDebug.logD("请手动断开网络,以触发重连")
                        continuation.resume(Result.success())

                    }

                    override fun onFailure(errorInfo: ErrorInfo) {
                        LogDebug.logE(errorInfo.toString())
                        LogOuter.print("number:$number \tresult:${false} \tname:CheckConnectState")
                        if (!continuation.isCompleted){
                            continuation.resume(Result.success())
                        }
                    }
                })

        checkConnectState(Connect.CONNECTION_STATE_CONNECTING, Connect.CONNECTION_CHANGE_REASON_LOGINING)


    }


    private fun checkConnectState(expectCode: Int, expectReason: Int) {
        if (TestInstance.connectStateCode == expectCode
                && TestInstance.connectStateReason == expectReason) {
            LogOuter.print("number:$number \tresult:${true} \tname:CheckConnectState")
        } else {
            LogOuter.print("number:$number \tresult:${false} \tname:CheckConnectState")
        }
    }


}